//
//  AttentionController.m
//  PropertyMananger
//
//  Created by bh on 16/12/29.
//  Copyright © 2016年 BH. All rights reserved.
//

#import "AttentionController.h"
#import "CustomSearchViewController.h"
#import "AttentionSearchResultViewController.h"
#import "AttentionModel.h"
#import "AttentionGrounpModel.h"
#import "AttentionCell.h"
#import "NSMutableArray+FilterElement.h"
#import "UIView+MCCommon.h"
#import "SearchResultHandle.h"
#import "AttentionDetailController.h"
#import "OnweDetailController.h"

@interface AttentionController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,UISearchBarDelegate,UISearchControllerDelegate,CustomSearchViewControllerDelegate,AttentionSearchResultViewControllerDelegate>
{
    UILabel *_indexView;//右边索引view
    NSMutableArray *_indexArr;//索引数组
}
@property (nonatomic,strong) NSMutableArray *dataArray; // 数据源大数组
@property (nonatomic,strong) CustomSearchViewController *searchController; // 搜索的控制器
@property (nonatomic,strong) NSMutableArray *searchList; // 搜索结果的数组
@property (nonatomic,strong) AttentionSearchResultViewController *resultViewController;//搜索的结果控制器
@property (nonatomic,strong) NSMutableArray *array; // 数据源数组 分组和每个区的模型
@property (nonatomic,strong) NSMutableArray *sectionIndexs; // 放字母索引的数组

@property (nonatomic,copy) NSString * Tel;//手机号
@property (nonatomic,copy) NSString * OfficeMobile;//分机号


@end

@implementation AttentionController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // [self initTitleViewName:@"通讯录"];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 0, BHscreenW, BHscreenH- 64) isGroup:NO];
    self.tableView.sectionIndexColor = [UIColor grayColor];
    
    // 创建搜索的控制器
    [self setupSearchController];
    
    
    // 加载数据源
    //   [self loadDatas];
    
    //通讯录数据源
    [self postAttentionData];
    
    
}
/**
 *  加载数据
 */
- (void)loadDatas
{
    self.array = [NSMutableArray array];
    NSMutableArray *tempArray = [NSMutableArray array];
    //  self.dataArray = [NSMutableArray arrayWithObjects:@"2dddddd",@"小雯",@"克",@"ssss",@"百度",@"腾讯",@"阿里巴巴",@"中智鸿博@163.com",@"@#3",@"mansionwayh",@"德克诺维茨基",@"谢璇",nil];
    
    
    self.sectionIndexs = [NSMutableArray array];
    for (NSString *string in self.dataArray) {
        
        NSString *header = [PinYinForObjc chineseConvertToPinYinHead:string];
        [self.sectionIndexs addObject:header];
    }
    // 去除数组中相同的元素
    self.sectionIndexs = [self.sectionIndexs filterTheSameElement];
    // 数组排序
    [self.sectionIndexs sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSString *string1 = obj1;
        NSString *string2 = obj2;
        return [string1 compare:string2];
    }];
    // 将排序号的首字母数组取出 分成一个个组模型 和组模型下边的一个个 item
    for (NSString *string in self.sectionIndexs) {
        AttentionGrounpModel *group = [AttentionGrounpModel getGroupsWithArray:self.dataArray groupTitle:string];
        if ([group.groupTitle isEqualToString:@"#"]) {
            // 默认 #开头的放在数组的最前边 后边才是 A-Z
            [tempArray insertObject:group atIndex:0];
        }else{
            [tempArray addObject:group];
        }
    }
    self.array = tempArray;
    [self.tableView reloadData];
}
/**
 *  初始化搜索控制器
 */
- (void)setupSearchController
{
    
    self.resultViewController = [[AttentionSearchResultViewController alloc] init];
    self.resultViewController.delegate = self;
    _searchController = [[CustomSearchViewController alloc] initWithSearchResultsController:self.resultViewController];
    _searchController.delegate = self;
    _searchController.delegateCustom = self;
    _searchController.searchResultsUpdater = self;
    
    _searchController.dimsBackgroundDuringPresentation = NO;
    _searchController.hidesNavigationBarDuringPresentation = NO;
    _searchController.searchBar.delegate = self;
    _searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 60.0);
    
    if (self.tag == 300)
    {
        _searchController.searchBar.placeholder = @"请输入物业人员姓名";
        self.resultViewController.index = TongXunLu;
        
    }else if (self.tag == 310)
    {
        _searchController.searchBar.placeholder = @"请输入业主姓名";
        self.resultViewController.index = YeZhuXinXi;
    }
    
    _searchController.searchBar.searchBarStyle = UISearchBarStyleDefault;
    
    _searchController.searchBar.returnKeyType = UIReturnKeyDone;
    _searchController.searchBar.backgroundImage = [[UIImage alloc] init];
    _searchController.searchBar.barTintColor  =[UIColor whiteColor];
    
    UITextField *searchField = [_searchController.searchBar valueForKey:@"searchField"];
    if (searchField) {
        [searchField setBackgroundColor:[UIColor whiteColor]];
        searchField.layer.cornerRadius = 4.0f;
        searchField.layer.borderColor = BHColor(200, 200, 200).CGColor;
        searchField.layer.borderWidth = 1;
        searchField.layer.masksToBounds = YES;
    }
    
    //3. 设置按钮文字和颜色
    [_searchController.searchBar fm_setCancelButtonTitle:@"取消"];
    _searchController.searchBar.tintColor = BHColor(102, 102, 102);
    
    //修正光标颜色
    [searchField setTintColor:BHColor(102, 102, 102)];
    
    //4. 设置输入框文字颜色和字体
    [_searchController.searchBar fm_setTextColor:BHColor(102, 102, 102)];
    [_searchController.searchBar fm_setTextFont:BHFont(13)];
    
    //5. 设置搜索Icon
    [_searchController.searchBar setImage:[UIImage imageNamed:@"ico_search"]
                         forSearchBarIcon:UISearchBarIconSearch
                                    state:UIControlStateNormal];
    
    self.tableView.tableHeaderView = _searchController.searchBar;
    
}

#pragma mark - 懒加载一些内容
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)searchList
{
    if (!_searchList) {
        _searchList = [NSMutableArray array];
    }
    return _searchList;
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.searchController.active?1:self.array.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchController.active) {
        return 0;
    }
    AttentionGrounpModel * group = self.array[section];
    return group.follows.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"FollwTableViewCell";
    AttentionCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[AttentionCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    AttentionGrounpModel *group = self.array[indexPath.section];
    AttentionModel *followM = group.follows[indexPath.row];
    cell.nameLabel.text = followM.RealName;
    cell.subtitle.text = followM.Duty;
    DLog(@"cell.subtitle.text == %@",cell.subtitle.text);
    //判断是通讯录还是业主信息
    if (self.tag == 300)
    {
        cell.iconImg.image = IMG(@"ico_mail_list_property");
        
    }else if (self.tag == 310)
    {
        cell.iconImg.image = IMG(@"ico_owner_inquiry");
    }
    
    return cell;
}
/**
 *   右侧的索引标题数组
 *
 *   @param tableView 标示图
 *
 *   @return 数组
 */
- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView
{
    return self.searchController.active?nil:self.sectionIndexs;
}
#pragma mark - UITableViewDelegate,点击查看详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"%ld===%ld",indexPath.section,indexPath.row);
    if (self.tag == 300)
    {//通讯录详情
        AttentionGrounpModel *group = self.array[indexPath.section];
        AttentionModel *followM = group.follows[indexPath.row];
        AttentionDetailController * detailVC = [[AttentionDetailController alloc]init];
        
        detailVC.model = followM;
        DLog(@"followM.Tel == %@",followM.Tel);
        detailVC.attentionTag = self.tag;
        [self.navigationController pushViewController:detailVC animated:YES];
        
    }else if (self.tag == 310)
    {//业主信息详细
        
        OnweDetailController * onwerDetailVC = [[OnweDetailController alloc]init];
        [self.navigationController pushViewController:onwerDetailVC animated:YES];
        
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    AttentionGrounpModel *group = self.array[section];
    // 背景图
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BHscreenW, 30)];
    bgView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    // 显示分区的 label
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, BHscreenW-40, 30)];
    label.text = group.groupTitle;
    label.font = BHFont(15);
    [bgView addSubview:label];
    return bgView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.searchController.active?0:30;
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
    
    NSString *searchString = [self.searchController.searchBar text];
    // 移除搜索结果数组的数据
    [self.searchList removeAllObjects];
    //过滤数据
    self.searchList= [SearchResultHandle getSearchResultBySearchText:searchString dataArray:self.dataArray];
    if (searchString.length==0&&self.searchList!= nil) {
        [self.searchList removeAllObjects];
    }
    self.searchList = [self.searchList filterTheSameElement];
    NSMutableArray *dataSource = nil;
    //    if ([self.dataArray count]>0) {
    //        dataSource = [NSMutableArray array];
    //        // 结局了数据重复的问题
    //
    //        for (NSString * str in self.searchList) {
    //            AttentionModel *model = [[AttentionModel alloc] init];
    //            model.RealName = str;
    //            model.img_Url = nil;
    //            model.Duty = str;
    //            model.Tel = str;
    //
    //            DLog(@"dataSource%@",dataSource);
    //            [dataSource addObject:model];
    //        }
    //
    //    }
    
    dataSource = [NSMutableArray array];
    for(int i = 0 ; i <self.searchList.count ; i++){
        
        NSString * realName = self.searchList[i];
        for(AttentionModel * model in self.dataArray){
            if([model.RealName isEqualToString:realName]){
                DLog(@"%@",model.Tel);
                [dataSource addObject:model];
            }
        }
    }
    
    //刷新表格
    self.resultViewController.dataSource = dataSource;
    //  [self.resultViewController.tableView reloadData];
    [self.tableView reloadData];
}

#pragma mark - 设置 tableViewcell横线左对齐
-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //[self searchControllerDissmiss];
    [self.view endEditing:YES];
    
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    
    //    DLog(@"点击取消");
    [self.searchController.searchBar resignFirstResponder];
    
    [self searchControllerDissmiss];
    
    
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    
    return YES;
}
//- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
//{
//  [self searchControllerDissmiss];
//}
#pragma mark - CustomSearchViewControllerDelegate
/**
 *  搜索控制器的自定义导航条返回按钮
 *
 *  @param searchController 搜索的控制器
 */
- (void)searchControllerBackButtonClick:(UISearchController *)searchController
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UserFollowSearchResultViewControllerDelegate
/**
 *  点击了搜索的结果的 cell
 *
 *  @param resultVC  搜索结果的控制器
 *  @param follow    搜索结果信息的模型
 */
- (void)resultViewController:(AttentionSearchResultViewController *)resultVC didSelectFollowModel:(AttentionModel *)follow
{
    [self searchControllerDissmiss];
    
    if (self.tag == 300)
    {//通讯录详情
        
        AttentionDetailController * detailVC = [[AttentionDetailController alloc]init];
        
        detailVC.model = follow;
        DLog(@"点击详情=== %@",follow.Tel);
        
        
        detailVC.attentionTag = self.tag;
        [self.navigationController pushViewController:detailVC animated:YES];
        
    }else if (self.tag == 310)
    {//业主信息详细
        
        OnweDetailController * onwerDetailVC = [[OnweDetailController alloc]init];
        [self.navigationController pushViewController:onwerDetailVC animated:NO];
        
    }
    
}
/**
 *  搜索的控制器消失了
 */
- (void)searchControllerDissmiss
{
    self.searchController.searchBar.text = @"";
    [self.searchController dismissViewControllerAnimated:YES completion:nil];
    
    
}
extern UserInfoModel const * userModel;
#pragma mark - 获取通讯录数据源
- (void)postAttentionData
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"努力加载数据中...";
    // 隐藏时从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.userInteractionEnabled = YES;
    
    NSDictionary * parms = @{@"PropertyID":userModel.PropertyID,
                             @"CommunityID":userModel.CommunityID,
                             @"json":@"\{\"jsonEntity\":\{},\"action\":\"getphonelist\",\"version\":\"V1.0\"}"};
    
    [HomeNetWorkRequest postAttentionSuccess:^(id data) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        
        DLog(@"通讯录信息的数据 == %@",array);
        
        for (NSDictionary * dict2 in array) {
            AttentionModel * model = [[AttentionModel alloc]init];
            [model setValuesForKeysWithDictionary:dict2];
            [self.dataArray addObject:model];
            DLog(@" === %@",model.RealName);
            
        }
        
        NSMutableArray *tempArray = [NSMutableArray array];
        
        
        self.sectionIndexs = [NSMutableArray array];
        for (AttentionModel * model in self.dataArray) {
            NSString *header = [PinYinForObjc chineseConvertToPinYinHead:model.RealName];
            [self.sectionIndexs addObject:header];
        }
        // 去除数组中相同的元素
        self.sectionIndexs = [self.sectionIndexs filterTheSameElement];
        // 数组排序
        [self.sectionIndexs sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            NSString *string1 = obj1;
            NSString *string2 = obj2;
            
            return [string1 compare:string2];
        }];
        // 将排序号的首字母数组取出 分成一个个组模型 和组模型下边的一个个 item
        for (NSString *string in self.sectionIndexs) {
            AttentionGrounpModel *group = [AttentionGrounpModel getGroupsWithArray:self.dataArray groupTitle:string];
            if ([group.groupTitle isEqualToString:@"#"]) {
                // 默认 #开头的放在数组的最前边 后边才是 A-Z
                [tempArray insertObject:group atIndex:0];
            }else{
                [tempArray addObject:group];
            }
        }
        self.array = tempArray;
        [self.tableView reloadData];
        
    } Fail:^(NSString *errorDes) {
        
        [MBProgressHUD hideHUD];
        
    } param:parms];
    
}

-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.searchController.searchBar resignFirstResponder];
    return indexPath;
}
// 滑动的时候 searchBar 回收键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.searchController.searchBar resignFirstResponder];
}

@end
